<template>
    <!-- 合同初稿 -->
    <CommonTitle
        titleName="合同初稿"
    ></CommonTitle>

    <div class="box">
        <el-form
            :disabled="getURLhandler(route.path).status!=='3' && getURLhandler(route.path).status!==''"
            v-loading="isLoading"
            element-loading-text="表单提交中..."
            :inline="true"
            label-width="140"
            :model="formInline"
            :rules="rules"
            ref="formRef"
            class="demo-form-inline"
        >
            <el-row>
                <el-col :span="8">
                    <el-form-item label="所属项目" prop="projectId">
                        <el-select
                            v-model="formInline.projectId"
                            placeholder="请选择项目"
                            filterable
                            clearable
                        >
                            <el-option v-for="(item,index) in state.projectList" :key="index" :label="item.projectName" :value="item.projectId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="合同名称" prop="contractName">
                        <el-input
                            :disabled="state.disabled"
                            v-model="formInline.contractName"
                            placeholder="请输入合同名称"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="合同编码" prop="contractNumber">
                        <el-input
                            v-model="formInline.contractNumber"
                            placeholder="请输入合同编码"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="合同类型" prop="typeContract">
                        <el-select
                            v-model="formInline.typeContract"
                            placeholder="请选择合同类型"
                        >
<!--                            <el-option label="招标合同" :value="1" />
                            <el-option label="投资合同" :value="2" />
                            <el-option label="建设合同" :value="3" />
                            <el-option label="其他合同" :value="4" />-->
                            <el-option label="设计合同" :value="5" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="合同子类" prop="contractChildCategory">
                        <el-select
                            v-model="formInline.contractChildCategory"
                            placeholder="请选择合同子类"
                            clearable
                            filterable
                        >
                            <el-option
                                v-for="item in state.contractSubtypeList"
                                :key="item"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="合同金额" prop="contractAmount">
                        <el-input
                            v-model="formInline.contractAmount"
                            @input="formInline.contractAmount = limitInputNum(formInline.contractAmount,10,5,true)"
                            placeholder="请输入合同金额"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="签订份数" prop="signNumber">
                        <el-input
                            v-model="formInline.signNumber"
                            @input="formInline.signNumber = limitInputNum(formInline.signNumber,10,0,true)"
                            placeholder="请输入签订份数"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="甲方单位" prop="signPartyA">
                        <el-input
                            :disabled="state.disabled"
                            v-model="formInline.signPartyA"
                            placeholder="请输入甲方单位"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="乙方单位" prop="signPartyB">
                        <el-input
                            :disabled="state.disabled"
                            v-model="formInline.signPartyB"
                            placeholder="请输入乙方单位"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="三方单位" prop="signPartyThree">
                        <el-input
                            :disabled="state.disabled"
                            v-model="formInline.signPartyThree"
                            placeholder="请输入三方单位"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="资金流向" prop="capitalFlow">
                        <el-select
                            v-model="formInline.capitalFlow"
                            placeholder=""
                        >
                            <el-option label="流入" :value="'1'" />
                            <el-option label="流出" :value="'2'" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="签约时间" prop="signTime">
                        <el-date-picker
                            v-model="formInline.signTime"
                            type="date"
                            placeholder="请选择签约时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="签约方式" prop="signingMethod">
                        <el-select
                            v-model="formInline.signingMethod"
                            placeholder="请选择合同签约方式"
                            filterable
                            clearable
                        >
                            <el-option
                                v-for="item in selectionTypeOptions"
                                :key="item"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8" >
                    <el-form-item label="周期时间" prop="serviceStartTime">
                        <el-date-picker
                            v-model="formInline.serviceStartTime"
                            type="datetimerange"
                            range-separator="-"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="合同概况" prop="contractContent">
                        <el-input
                            v-model="formInline.contractContent"
                            type="textarea"
                            placeholder="请输入合同内容"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="支付方式说明" prop="payExplain">
                        <el-input
                            v-model="formInline.payExplain"
                            type="textarea"
                            placeholder="请输入支付方式说明"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="签约方式说明" prop="signExplain">
                        <el-input
                            v-model="formInline.signExplain"
                            type="textarea"
                            placeholder="请输入签约方式说明"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="合同附件" prop="files">
                        <FileMinioUpload
                            :restriction="true"
                            :restrictionLimit="9"
                            v-model:files="formInline.files"
                            :disabled="getURLhandler(route.path).status!=='3' && getURLhandler(route.path).status!==''"
                            :show-button="!(getURLhandler(route.path).status!=='3' && getURLhandler(route.path).status!=='')"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <div style="width: 100%;" class="d-flex a-center j-center">
            <el-button type="primary" @click="goback" class="button_cancel2"> 取消 </el-button>
            <el-button v-if="getURLhandler(route.path).status===''" class="button_view" @click="onSubmit()">提交</el-button>
            <el-button v-if="getURLhandler(route.path).status==='3'" class="button_view" @click="onSubmit()">编辑</el-button>
        </div>
    </div>
</template>

<script setup>
import {darkLine, department, designProject} from '@/api/project'

import { ref, reactive, onMounted } from 'vue'
import {
    ElMessage,
    ElDatePicker,
    ElRow,
    ElCol,
    ElForm, ElMain
} from 'element-plus'
import CommonTitle from '@/components/CommonTitle.vue'
import { useRouter, useRoute } from 'vue-router'
import FileMinioUpload from "@/components/FileMinioUpload.vue";
import {
    getURLhandler,
    nanoid
} from '@/views/constructionProjectManage/static/utools.js'
import {limitInputNum} from "@/common/utils/GlobalUtils";
import {selectionTypeOptions} from "@/common/dict/dictCollect";

let router = useRouter()
let route = useRoute()

const isLoading = ref(false);

const state = reactive({
    projectList:[],
    contractSubtypeList:[
        {
            label: '设计合同',
            value: '1'
        },
        {
            label: '图审合同',
            value: '2'
        },
        {
            label: '勘察合同',
            value: '3'
        },
        {
            label: '测绘合同',
            value: '4'
        },
        {
            label: '安评合同',
            value: '5'
        },
        {
            label: '资讯合同',
            value: '6'
        },
        {
            label: '鉴定合同',
            value: '7'
        },
        {
            label: '策划合同',
            value: '8'
        },
        {
            label: '其他合同',
            value: '9'
        }
    ],
    auditStatus: [
        {
            label: '待审核',
            value: '1'
        },
        {
            label: '审核成功',
            value: '2'
        },
        {
            label: '审核驳回',
            value: '3'
        }
    ],
    user: '',
    projectTaskId: '',
    projectId: '',
    itemId: '',
    type: '',
    // payItem: {
    //   term: '',
    //   // moneyFlowType: 1,
    //   settlementStartTime: [],
    //   payId: nanoid()
    // },
    disabled: false
})
const formInline = reactive({
    files: [],
    examineStatus:'1',
    approvalFormCode: '', //审核结果相关字段
    apparovalStatus: '' //审核结果相关字段
})
const rules = {
    projectId: [
        { required: true, message: '所属项目不能为空', trigger: 'blur' }
    ],
    signNumber: [
        { required: true, message: '签订份数不能为空', trigger: 'blur' }
    ],
    serviceStartTime: [
        { required: true, message: '请选择周期时间', trigger: 'change' }
    ],
    capitalFlow: [
        { required: true, message: '请选择资金流向', trigger: 'change' }
    ],
    contractChildCategory: [
        { required: true, message: '请选择合同子类', trigger: 'change' }
    ],
    contractName: [
        { required: true, message: '合同名称不能为空', trigger: 'blur' }
    ],
    signingMethod: [
        { required: true, message: '签约方式不能为空', trigger: 'blur' }
    ],
    typeContract: [
        { required: true, message: '合同类型不能为空', trigger: 'blur' }
    ],
    contractNumber: [
        { required: true, message: '合同编码不能为空', trigger: 'blur' }
    ],
    signPartyA: [
        { required: true, message: '签约甲方不能为空', trigger: 'blur' }
    ],
    signPartyB: [
        { required: true, message: '签约乙方不能为空', trigger: 'blur' }
    ],

    contractAmount: [
        { required: true, message: '合同金额不能为空', trigger: 'blur' }
    ],
    signTime: [
        { required: true, message: '合同签订日期不能为空', trigger: 'blur' }
    ],
   /* contractContent: [
        { required: true, message: '合同概况不能为空', trigger: 'blur' }
    ],*/
   /* payExplain: [
        { required: true, message: '支付方式说明不能为空', trigger: 'blur' }
    ],*/
    remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
    files: [{ required: true, message: '附件不能为空', trigger: 'blur' }],
    contractAmountDescription: [
        { required: true, message: '合同金额描述不能为空', trigger: 'blur'}
    ],
    contractAgreementCategory: [
        { required: true, message: '请选择合同/协议类别', trigger: 'blur'}
    ],
    responsibleDepartmentId: [
        { required: true, message: '请选择合同归属部门', trigger: 'blur'}
    ],
}
// 1, "公开招标
// 2, "公开竞争性谈判
// 3, "公开竞争性磋商
// 4, "择优比选"
// 5, "单一来源采购
// 6, "邀请竞争性谈判
// 7, "邀请竞争性磋商
// 8, "择优询价"
// 9, "单一来源采购
const projectTendersWayList = reactive([
    {
        label: '公开招标',
        value: '1'
    },
    {
        label: '公开竞争性谈判',
        value: '2'
    },
    {
        label: '公开竞争性磋商',
        value: '3'
    },
    {
        label: '择优比选',
        value: '4'
    },
    {
        label: '单一来源采购',
        value: '5'
    },
    {
        label: '邀请竞争性谈判',
        value: '6'
    },
    {
        label: '邀请竞争性磋商',
        value: '7'
    },
    {
        label: '择优询价',
        value: '8'
    },
    {
        label: '单一来源采购',
        value: '9'
    }
])

const typeArr = [
    {
        label: '修缮改造类（非工程建设）',
        value: 1
    },
    {
        label: '物资采购类（非工程建设）',
        value: 2
    },
    {
        label: '物业服务类（非工程建设）',
        value: 3
    },
    {
        label: '其他服务类（非工程建设）',
        value: 4
    },
    {
        label: '设施设备系统维保及维修类（非工程建设）',
        value: 5
    },
    {
        label: '施工类（工程建设）',
        value: 6
    },
    {
        label: '与工程建设有关的重要设备、材料等货物采购类（工程建设）',
        value: 7
    },
    {
        label: '勘察、设计、监理服务类（工程建设）',
        value: 8
    },
    {
        label: '检查、检测、咨询、测绘、图审等其他工程服务类（工程建设）',
        value: 9
    },
    {
        label: '资产租售类',
        value: 10
    },
    {
        label: '办公物资类',
        value: 11
    },
];
const tableData = ref([]);
// term: '',
//     moneyFlowType: 0,
//     settlementStartTime: [],
//     payId: nanoid()
const tableHead = ref([
    {
        prop: 'term',
        label: '期数'
    },
    {
        prop: 'settlementStartTime',
        label: '付款范围',
        formatter: (row) => {
            return row.settlementStartTime.join('-')
        }
    },
    {
        prop: 'payableAmount',
        label: '金额'
    }
])
const handel = () => {}
const deleteHandler = (row) => {
    tableData.value = tableData.value.filter((item) => item.payId !== row.payId)
}
const addRow = () => {
    state.payItem.payId = nanoid()
    tableData.value.push(JSON.parse(JSON.stringify(state.payItem)))
}
const goback = () => {
    router.go(-1)
}


const formRef = ref(null)
const onSubmit = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            isLoading.value = true;
            let params = {
              ...formInline
            };
            if(Array.isArray(formInline.serviceStartTime) && formInline.serviceStartTime.length){
                params.serviceStartTime = formInline.serviceStartTime[0];
                params.serviceEndTime = formInline.serviceStartTime[1];
            }
            designProject.addAndEditDesign(params).then(res=>{
                isLoading.value = false;
                if(res.code === '200'){
                    router.push({path:`/designManagement/contractInformation/index`})
                    ElMessage.success('操作成功');
                }
            });
        }
    })
}


// 获取合同归属部门选项
let departmentArr = ref([]);
let getAllDepartments = async() => {
    let { data } = await department.getAllDepartments();
    departmentArr.value = data
}

/**
 * 查询项目列表
 */
const getProjectList = () => {
    darkLine.getProjectList().then(res=>{
        if(res.code==='200'){
            state.projectList = res.data;
        }
    });
}

/**
 * 初始化
 */
const initForm = () => {
    if(getURLhandler(route.path).contractId){
        designProject.viewContract({contractId:getURLhandler(route.path).contractId}).then(res=>{
            for(let key in res.data){
                if(key==='serviceStartTime'){
                    formInline[key] = [res.data['serviceStartTime'],res.data['serviceEndTime']]
                }else if(key==='fileList'){
                    formInline['files'] = res.data[key];
                }else{
                    formInline[key] = res.data[key];
                }
            }
        });
    }
}

onMounted(() => {
    getProjectList();
    initForm();
})
</script>

<style lang="scss" scoped>
.el-form-item,
.el-select {
    width: 100%;
}
.box {
    border-radius: 10px;
    border: 1px solid #e3e7f1;
    padding: 34px 90px;
}
.table_class {
    margin-top: 20px;
    margin-bottom: 20px;
}
:deep(.el-input__wrapper) {
    width: 100%;
    height: 40px;
}
:deep(.el-date-editor) {
    width: 100%;
    height: 40px;
}
</style>
